﻿using MyMVC.attr;
using MyMVC.handler;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;

namespace MyMVC.mapper
{
    public class ActionMapper
    {
        private MethodInfo m;

        public ActionMapper(MethodInfo m, string url, Type baseType)
        {
            this.m = m;
            this.Url = url;
            this.BaseType = baseType;
            if (m.ReturnType.Equals(typeof(ModelAndView)))
                this.ReturnType = "view";
            else if (m.ReturnType.Equals(typeof(JSON)))
                this.ReturnType = "json";
            else
                this.ReturnType = "void";
        }
        public string Url { get; set; }

        public Type BaseType { get; set; }

        public string ReturnType { get; set; }

        internal IHttpHandler CreateHandler(HttpContext context, Dictionary<Type, Type> dictionary)
        {
            ActionSupport obj = (ActionSupport)Activator.CreateInstance(this.BaseType);
            FieldInfo[] fields = this.BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            if (fields != null && fields.Length > 0)
            {
                object obj2;
                foreach (FieldInfo f in fields)
                {
                    obj2 = getAttribute(f, typeof(AutoWired));
                    if (obj2 != null)
                    {
                        f.SetValue(obj, Activator.CreateInstance(dictionary[f.FieldType]));
                    }
                }
            }
            if (this.ReturnType.Equals("view"))
                return new ViewHandler(context, this.m, obj);
            if (this.ReturnType.Equals("json"))
                return new JsonHandler(context, this.m, obj);
            if (this.ReturnType.Equals("void"))
                return new VoidHandler(context, this.m, obj);
            return null;
        }

        private static object getAttribute(FieldInfo f, Type type)
        {
            object[] objs = f.GetCustomAttributes(type, false);
            if (objs != null && objs.Length > 0)
            {
                return objs[0];
            }
            return null;
        }
    }
}
